<template>
  <div class='login'>
    <div class="title">
      请登录
    </div>
    <van-form
      :show-error="false"
      :show-error-message="false"
      @failed="onFailed"
      @submit="onSubmit"
      v-show="isShowLoginMode"
    >
      <van-field
        v-model="phone"
        name="用户名"
        placeholder="请输入手机号"
        :rules="formRules.phone"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        placeholder="密码"
        :rules="formRules.password"
      />
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
      <div class="loginModeTip" @click="isShowLoginMode = false">
        扫描二维码
      </div>
    </van-form>

    <div v-if="!isShowLoginMode">
      <div class="qrShow">
        <van-image
          :src="qrCode"
          @error="qrCode = ''"
        >
          <template v-slot:error>
            <p @click="qrLogin">加载失败，点击重试。</p>
          </template>
        </van-image>
      </div>
      <p class="scanQRstatusTip"> {{ scanStatus }}</p>
      <div class="loginModeTip" @click="isShowLoginMode = true">
        密码登录
      </div>
    </div>
  </div>
</template>

<script>
import { Form, Field, Button, Toast, Image as VanImage } from 'vant'
import { login, loginStatus, getQRKey, createQR, checkQRStatus } from '@/api/login'

export default {
  name: 'login',
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Button.name]: Button,
    [Toast.name]: Toast,
    [VanImage.name]: VanImage
  },
  props: {},
  data () {
    return {
      phone: '17694465256',
      password: '1161512878wy',
      // 手机和密码的检验规则
      formRules: {
        phone: [
          { required: true, message: '请输入手机号' },
          { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '手机号格式错误' }
        ],
        password: [
          { required: true, message: '请填写密码' }
        ]
      },
      isShowLoginMode: true, // 判断当前展示的登录页面
      qrCode: '', // 二维码64位代码
      checkQRStatusTimer: null, // 检测二维码扫描状态的定时器
      scanStatus: '' // 二维码扫描状态的提示文字
    }
  },
  computed: {},
  watch: {
    // 监测当前显示的登录方式
    isShowLoginMode: function () {
      if (!this.isShowLoginMode) {
        this.qrLogin()
      } else {
        // 非二维码登录方式，将‘检测扫码的状态’的定时器清除
        clearInterval(this.checkQRStatusTimer)
      }
    }
  },
  created () {},
  mounted () {},
  methods: {
    // 登录，登录成功后返回上一层
    async onSubmit () {
      Toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data } = await login({
          phone: this.phone,
          password: this.password,
          timestamp: new Date().getTime()
        })
        this.$store.commit('setLoginData', data)
        console.log(data)
        if (data.code === 502) {
          return Toast.fail('密码错误')
        }
        Toast.success('登录成功')
        this.$router.back()
      } catch (err) {
        let message = '登录失败'
        const data = err.response.data
        // 509：密码错误次数过多; 501：账号不存在
        if (data.code === 509) {
          message = data.message
        } else if (data.code === 501) {
          message = data.message
        }
        Toast.fail(message)
      }
    },
    // 提交表单且验证不通过
    onFailed (err) {
      if (err.errors[0]) {
        Toast.fail(err.errors[0].message)
      }
    },

    // 二维码登录
    async qrLogin () {
      // 获取二维码 key
      const { data } = await getQRKey()
      const qrKey = data.data.unikey
      // 发送请求（二维码 key），在页面中生成二维码（base64）
      const getQrimg = await createQR(qrKey)
      this.qrCode = getQrimg.data.data.qrimg
      // 检测扫码状态
      this.checkQRStatusTimer = setInterval(async () => {
        const data = await checkQRStatus(qrKey)
        const code = data.data.code
        this.scanStatus = '等待扫码'
        // 判断扫码状态；800 为二维码过期，801 为等待扫码，802 为待确认，803 为授权登录成功
        if (code === 800) {
          clearInterval(this.checkQRStatusTimer)
          this.scanStatus = data.data.message
          this.qrCode = ''
        } else if (code === 802) {
          this.scanStatus = data.data.message
        } else if (code === 803) {
          clearInterval(this.checkQRStatusTimer)
          const res = await loginStatus(data.data.cookie)
          this.$store.commit('setLoginData', res.data.data)
          Toast.success('登录成功')
          this.$router.back()
        }
      }, 3000)
    }
  }
}
</script>
<style lang='less' scoped>
@import "../../styles/common.less";
.login {
  .title {
    line-height: 160px;
    font-size: 25px;
    padding: 0 30px;
    font-weight: bold;
    letter-spacing: 4px;
    color: @themeColor;
  }
  /deep/ .van-field__control {
    line-height: 50px;
    border: 2px @themeColor solid;
    border-radius: 30px;
    font-size: 16px;
    padding: 0px 20px;
  }
  .van-button {
    margin-top: 20px;
    height: 53px;
    font-size: 19px;
    font-weight: 600;
    letter-spacing: 4px;
  }
  .loginModeTip {
    display: block;
    font-size: 12px;
    line-height: 30px;
    text-align: center;
    color: #8a8a8a;
  }
  .scanQRstatusTip {
    height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 15px;
  }
  .qrShow {
    height: 150px;
    width: 150px;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    /deep/ .van-image__error {
      width: 120px;
      height: 120px;
      padding: 10px;
      position: unset;
      background: rgba(180, 38, 38, 0.2);
      text-align: center;
      font-size: 20px;
      color: #ffffff;
    }
  }
}
</style>
